package com.pengpeng.rabbitmq.declare;

import com.pengpeng.rabbitmq.bean.MqExchange;
import com.pengpeng.rabbitmq.exception.RabbitMQException;
import com.pengpeng.rabbitmq.constants.ExchangeTypeConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 彭鹏
 * @date 2021/10/19.
 */
@Component
public class AmExchangeDeclare extends AbstractDeclare {

    @Autowired
    RabbitAdmin rabbitAdmin;
    /**
     * 向rabbitMQ服务器注册指定的交换机以及交换机的类型
     *
     * @param mqExchange
     * @return
     */
    public Exchange declareExchange(MqExchange mqExchange) {
        this.logger.info("declare exchange is :" + mqExchange.toString());

        Exchange exchange = null;

        super.validate(mqExchange);
        exchange = this.initExchange(mqExchange);
        this.rabbitAdmin.declareExchange(exchange);

        this.logger.info("declare exchange success");
        return exchange;
    }


    /**
     * 从RabbitMQ服务端上删除指定的交换机
     *
     * @param exchangeName
     * @return
     */
    public boolean deleteExchange(String exchangeName) {
        this.logger.info("delete exchange is : " + exchangeName);

        if (StringUtils.isEmpty(exchangeName)) {
            throw new RabbitMQException("the parameter exchangeName couldn't not be null");
        }

        return this.rabbitAdmin.deleteExchange(exchangeName);
    }

    /**
     * 根据不同类型初始化不同类型的交换机
     *
     * @param mqExchange
     * @return
     */
    private Exchange initExchange(MqExchange mqExchange) {
        String exchangeType = mqExchange.getType();
        switch (exchangeType) {
            case ExchangeTypeConstants.DIRECT:
                return new DirectExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
            case ExchangeTypeConstants.TOPIC:
                return new TopicExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
            case ExchangeTypeConstants.FANOUT:
                return new FanoutExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
            case ExchangeTypeConstants.HEADERS:
                return new HeadersExchange(mqExchange.getName(), mqExchange.isDurable(), mqExchange.isAutoDelete(), mqExchange.getArguments());
            default:
                return null;
        }
    }

    /**
     * 自定义校验规则
     *
     * @param object
     */
    @Override
    public void DefinedValidate(Object object) {

    }
}
